/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;

import dp1.titandevelop.titano.bean.Estado;
import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Almacen;
import dp1.titandevelop.titano.persistent.AlmacenXProducto;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.service.AlmacenService;
import dp1.titandevelop.titano.service.AlmacenXProductoService;
import dp1.titandevelop.titano.service.ProductoService;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author dorita
 */
public class DetalleAlmacenes extends javax.swing.JInternalFrame {
    ProductoService sp = new ProductoService();
    AlmacenXProductoService spa = new AlmacenXProductoService();
    AlmacenService sa = new AlmacenService();
    Producto producto;
    
     private ArrayList<AlmacenXProducto> listaAlmcenes;
    private ArrayList<AlmacenXProducto> listaAlmacenEliminados;/**
     * Creates new form DetalleAlmacenes
     */
    public DetalleAlmacenes(Producto p) {
        initComponents();
        this.producto =p;
        this.listaAlmacenEliminados = new ArrayList<AlmacenXProducto>();
        this.listaAlmcenes= this.sp.buscaAlmacenes(p);
        this.tblAlmacenes.setModel(this.modeloAlmacen);
        this.txtProducto.setText(p.getDescripcion());
        this.txtProducto.setEnabled(false);
        
    }
    
    public void RefrescarTablaAlmacen() {
        
        AbstractTableModel aux = (AbstractTableModel) this.tblAlmacenes.getModel();
           // this.inhabilitaBotones();
        aux.fireTableDataChanged();
        }
    
     //Llena nuevos insumos a la lista de almacenes
    public void Llenar_Almacenes(Almacen a, int capacidad) {
        //listaAlmacenes.add(p);
        //Crea el objeto receta para pasarlo a la lista a apartir del insumo ingresado
        AlmacenXProducto ap =new AlmacenXProducto();
        ap.setToAlmacen(a);
        ap.setCapacidad(capacidad);
        ap.setStock(0);
        Estado e=new Estado();
        ap.setEstado(e.getActivo());
        
        listaAlmcenes.add(ap);
        
       }
    private AbstractTableModel modeloAlmacen = new AbstractTableModel() {
        public int getRowCount() {
            if (listaAlmcenes!=null)
            return listaAlmcenes.size();
            else return 0;
        }

        public int getColumnCount() {
        return 2;
        }

        String [] titles = {"Almacen","Capacidad"};

        @Override
        public boolean isCellEditable(int row, int column) {
           
                return ( column == 1 ); 
        }
     
        public void setValueAt(Object value, int row, int col) {
            if ( col == 1 ) {           
                AlmacenXProducto r=listaAlmcenes.get(row);
                r.setCapacidad(Integer.parseInt(""+value));
                listaAlmcenes.set(row, r);
            }
            this.fireTableDataChanged();
        };
        public String getColumnName(int col){
        return titles[col];
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
        //String res=null;
        AlmacenXProducto ap=listaAlmcenes.get(rowIndex);
            switch (columnIndex){
            case 0: return ap.getToAlmacen().getDescripcion();
            case 1: return ap.getCapacidad();
            }
            return null;
            } 
    };

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlAlmacenes = new javax.swing.JPanel();
        btnDetalleAlmacen = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblAlmacenes = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txtProducto = new javax.swing.JTextField();

        setResizable(true);
        setTitle("Agregar a Almacén");
        setPreferredSize(new java.awt.Dimension(523, 300));

        pnlAlmacenes.setBorder(javax.swing.BorderFactory.createTitledBorder("Almacenes"));

        btnDetalleAlmacen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnDetalleAlmacen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleAlmacenActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        tblAlmacenes.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        tblAlmacenes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tblAlmacenes);

        jLabel1.setText("Producto a Asignar:");

        txtProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProductoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlAlmacenesLayout = new javax.swing.GroupLayout(pnlAlmacenes);
        pnlAlmacenes.setLayout(pnlAlmacenesLayout);
        pnlAlmacenesLayout.setHorizontalGroup(
            pnlAlmacenesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlAlmacenesLayout.createSequentialGroup()
                .addGroup(pnlAlmacenesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlAlmacenesLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(pnlAlmacenesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlAlmacenesLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(txtProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnDetalleAlmacen))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlAlmacenesLayout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jButton1)
                                .addGap(0, 0, 0)
                                .addComponent(jButton2))))
                    .addComponent(jScrollPane2))
                .addContainerGap())
        );
        pnlAlmacenesLayout.setVerticalGroup(
            pnlAlmacenesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlAlmacenesLayout.createSequentialGroup()
                .addGroup(pnlAlmacenesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnDetalleAlmacen)
                    .addGroup(pnlAlmacenesLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(pnlAlmacenesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlAlmacenesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(pnlAlmacenes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlAlmacenes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnDetalleAlmacenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleAlmacenActionPerformed
        // TODO add your handling code here:
        Frame f = JOptionPane.getFrameForComponent(this);
        ModulosT_PRO_BuscarAlmacenes dialog = new ModulosT_PRO_BuscarAlmacenes(f,true, listaAlmcenes);
        //this.getParent().add(dialog);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnDetalleAlmacenActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        //Actualiza almacenes
        Mensajes m = new Mensajes();
        ArrayList<AlmacenXProducto> listaAgregarA = new ArrayList<AlmacenXProducto>();
        ArrayList<AlmacenXProducto> listaActualizarA = new ArrayList<AlmacenXProducto>();
        this.sp.EliminaAlmacenes(this.listaAlmacenEliminados);
        //Luego seleccionamos los elementos de la lista que seran editados y los que seran agregados
        for (int i=0; i<this.listaAlmcenes.size();i++)
        {
           System.out.println("id="+producto.getIdproducto());
            AlmacenXProducto r = spa.buscarPorIdAlm_IdProd(producto.getIdproducto(), listaAlmcenes.get(i).getToAlmacen().getIdalmacen());
            if (r!=null)
            {
                System.out.println("ikiii");
                //Editamos los elementos existentes
                listaActualizarA.add(this.listaAlmcenes.get(i));
            }
            else listaAgregarA.add(this.listaAlmcenes.get(i));
        }
        //Editamos
        this.sp.ActualizaAlmacenes(listaActualizarA);
        
         
        //Luego agregamos los insumos nuevos
        this.sp.InsertaEnAlmacenes(producto.getIdproducto(), listaAgregarA);
         // TODO add your handling code here:
         ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
        this.getParent().add( ModulosT_PRO.AdmProductos);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
         ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);

         ModulosT_PRO.AdmProductos.show();
        ModulosT_PRO.detalleAlmacen=null;
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
         // TODO add your handling code here:
         ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
        this.getParent().add( ModulosT_PRO.AdmProductos);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
         ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);

         ModulosT_PRO.AdmProductos.show();
        ModulosT_PRO.detalleAlmacen=null;
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void txtProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProductoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtProductoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDetalleAlmacen;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel pnlAlmacenes;
    private javax.swing.JTable tblAlmacenes;
    private javax.swing.JTextField txtProducto;
    // End of variables declaration//GEN-END:variables
}
